package com.maizi.thread;



import java.util.concurrent.locks.Lock;

/**
 * 案例地址: https://www.jianshu.com/p/56b24b623d02
 * 案例2地址:https://www.cnblogs.com/cj8357475/p/16086046.html
 */
public class ThreadTest implements Runnable {
    int number = 10;
 
    public void firstMethod() throws Exception {

        synchronized (this) {
            System.out.println("进入线程:{}的run方法中---------"+Thread.currentThread().getName());
            Thread.sleep(5000);
            number += 100;
            System.out.println("当前线程的名称:{}+当前线程的状态为:{}+当前打印的number值:{}"+Thread.currentThread().getName()+Thread.currentThread().getState()+number);
            //this.notify();
        }
    }
 
    public void secondMethod() throws Exception {
        //cas自选锁的优势:当前线程不需要进入等待状态+重新被唤醒然后执行+节省线程的开销
        //缺点:浪费了cpu的资源
            synchronized (this) {
                System.out.println("进入普通方法中---------");
                /**
                 * (休息2S+阻塞线程)
                 * 以验证当前线程对象的机锁被占用时+
                 * 是否被可以访问其他同步代码块
                 */
                //Thread.sleep(2000);
                this.wait(2000);
                number *= 200;
                System.out.println("普通方法中number值为:{}"+ number);
            }
    }
 
    @Override
    public void run() {
        try {
            firstMethod();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) throws Exception {

        //ThreadTest threadTest = new ThreadTest();
        //Thread thread = new Thread(threadTest);
        //System.out.println("启动前线程状态--------------:"+thread.getState()); // 获取启动前的状态

       // System.out.println("number=:"+threadTest.number);



        // 线程启动
        //thread.start();
        //thread.join();
       // System.out.println("启动后线程状态--------------:"+thread.getState());// 获取启动时的状态
        //threadTest.secondMethod();
//        while (thread.getState()!=Thread.State.TERMINATED){
//            Thread.sleep(900); // 延时100ms刷新状态
//            System.out.println("休眠中线程状态--------------:"+thread.getState());
//
//        }

    }
}